<?php

namespace Eduxplus\CmsBundle\Controller\Admin;

use Eduxplus\CoreBundle\Lib\Base\BaseAdminController;
use Eduxplus\CoreBundle\Lib\Form\Form;
use Eduxplus\CoreBundle\Lib\Grid\Grid;
use Eduxplus\CoreBundle\Service\UserService;
use Eduxplus\CmsBundle\Service\Admin\TutorialCategoryService;
use Eduxplus\CmsBundle\Service\Admin\TutorialService;
use Symfony\Component\HttpFoundation\Request;
use Eduxplus\CoreBundle\Service\DraftService;

class TutorialController extends BaseAdminController
{
    const DRAFT_TYPE = 300;

    public function indexAction(Request $request, Grid $grid, TutorialService $tutorialService, UserService  $userService, TutorialCategoryService $tutorialCategoryService)
    {
        $pageSize = 40;
        $grid->setListService($tutorialService, "getList");
        $grid->text("ID")->field("id")->sort("a.id");
        $grid->text("教程名称")->field("name")->sort("a.name");
        $grid->text("类目")->field("category");
        $grid->text("类型")->field("type")->sort("a.type")->options([1 => "章节教程", 2 => "速查表"]);
        $grid->image("封面图")->field("bigImg");
        $grid->text("创建人")->field("creater");
        $grid->text("排序")->field("sort");
        $grid->boole2("上架？")->field("status")->actionCall("admin_api_cms_tutorial_switchStatus", function ($obj) use($tutorialService) {
            $id = $tutorialService->getPro($obj, "id");
            $defaultValue = $tutorialService->getPro($obj, "status");
            $url = $this->generateUrl('admin_api_cms_tutorial_switchStatus', ['id' => $id]);
            $checkStr = $defaultValue ? "checked" : "";
            $confirmStr = $defaultValue ? "确认要下架吗？" : "确认要上架吗?";
            $str = "<input type=\"checkbox\" data-bootstrap-switch-ajaxput href=\"{$url}\" data-confirm=\"{$confirmStr}\" {$checkStr} >";
            return $str;
        });
        
        $grid->datetime("创建时间")->field("createdAt")->sort("a.createdAt");
        
        $grid->setTableAction('admin_cms_tutorial_chapter_index', function ($obj) use($tutorialService){
            $id = $tutorialService->getPro($obj, "id");
            $url = $this->generateUrl('admin_cms_tutorial_chapter_index', ['id' => $id]);
            $str = '<a href="javascript:;" data-url=' . $url . ' title="章节"  class=" btn btn-info btn-xs newTab"><i class="mdi mdi-book"></i>章节</a>';
            return  $str;
        });
        $grid->editAction('admin_cms_tutorial_edit');
        $grid->deleteAction("admin_api_cms_tutorial_delete");
        //批量删除
        $grid->setBathDelete("admin_api_cms_tutorial_bathdelete");

        $grid->gbAddButton("admin_cms_tutorial_add" ,[],self::DRAFT_TYPE);

        //搜索
        $select = $tutorialCategoryService->categorySelect();

        $grid->snumber("ID")->field("a.id");
        $grid->stext("教程名称")->field("a.name");
        $grid->sselect("上架？")->field("a.status")->options(["全部" => -1, "下架" => 0, "上架" => 1]);
        $grid->ssearchselect("创建人")->field("a.createUid")->options(function () use ($request, $userService) {
            $values = $request->get("values");
            $createUid = ($values && isset($values["a.createUid"])) ? $values["a.createUid"] : 0;
            if ($createUid) {
                $users = $userService->searchResult($createUid);
            } else {
                $users = [];
            }
            return [$this->generateUrl("admin_api_glob_searchAdminUserDo"), $users];
        });

        $grid->sselect("类别")->field("a.categoryId")->options($select);
        $grid->sdaterange("创建时间")->field("a.createdAt");
        return $this->content()->renderList($grid->create($request, $pageSize));
    }

    public function addAction(Form $form, TutorialService $tutorialService, TutorialCategoryService $tutorialCategoryService)
    {
        $form->text("教程名称")->field("name")->isRequire(1);
        $form->richEditor("简介")->attr(["height"=>600])->field("descr");
        $form->select("类型")->field("type")->isRequire(1)->options( ["章节教程"=>1, "速查表"=>2]);

        $options = [];
        $options["data-upload-url"] = $this->generateUrl("admin_glob_upload", ["type" => "img_course"]);
        $options["data-min-file-count"] = 1;
        $options['data-max-total-file-count'] = 1;
        $options["data-max-file-size"] = 1024 * 5; //5m
        $options["data-required"] = 0;
        $form->file("封面图")->field("bigImg")->attr($options);

        $form->select("类目")->field("categoryId")->isRequire(1)->options($tutorialCategoryService->categorySelect());
        $form->text("排序")->field("sort")->isRequire(1)->defaultValue(0);
        $form->boole("上架？")->field("status")->isRequire(1);
        $formData = $form->create($this->generateUrl("admin_api_cms_tutorial_add"));
        return $this->content()->title("添加教程")
            ->draftType(self::DRAFT_TYPE)
            ->breadcrumb("教程管理", "admin_cms_tutorial_index")
            ->renderAdd($formData);
    }


    public function addDoAction(Request $request, TutorialService $tutorialService, DraftService $draftService)
    {
        $name = $request->get("name");
        $bigImg = $request->get("bigImg");
        $descr = $request->get("descr");
        $categoryId = (int) $request->get("categoryId");
        $type = (int) $request->get("type");
        $status = $request->get("status");
        $sort = (int) $request->get("sort");
        $status = $status == "on" ? 1 : 0;

        if (!$name) return $this->responseError("教程名称不能为空!");
        if (mb_strlen($name, 'utf-8') > 50) return $this->responseError("教程名称不能大于50字!");
        if ($categoryId <= 0) return $this->responseError("请选择分类!");

        $uid = $this->getUid();
        $tutorialService->add($uid, $name, $type,$bigImg, $descr, $categoryId, $status, $sort);

        if($this->error()->has()){
            return $this->responseError($this->error()->getLast());
        }
        
        $draftService->del4Complete($request, $this->getUid());
        return $this->responseMsgCloseTab("操作成功!");
    }


    public function editAction($id, Form $form, TutorialService $tutorialService,  TutorialCategoryService $tutorialCategoryService)
    {
        $info = $tutorialService->getById($id);

        $form->text("教程名称")->field("name")->isRequire(1)->defaultValue($info['name']);
        $form->select("类型")->field("type")->isRequire(1)->options( ["章节教程"=>1, "速查表"=>2]);
        $form->richEditor("简介")->field("descr")->attr(["height"=>600])->defaultValue($info['descr']);

        $options = [];
        $options["data-upload-url"] = $this->generateUrl("admin_glob_upload", ["type" => "img_course"]);
        $options["data-min-file-count"] = 1;
        $options['data-max-total-file-count'] = 1;
        $options["data-max-file-size"] = 1024 * 5; //2m
        $options["data-required"] = 0;
        $options['data-initial-preview'] = $info["bigImg"];
        $options['data-initial-preview-config'] = $tutorialCategoryService->getInitialPreviewConfig($info['bigImg']);
        $form->file("封面图")->field("bigImg")->attr($options)->defaultValue($info['bigImg']);

        $form->select("类目")->field("categoryId")->isRequire(1)->options($tutorialCategoryService->categorySelect())->defaultValue($info['categoryId']);
        $form->text("排序")->field("sort")->isRequire(1)->defaultValue($info['sort']);
        $form->boole("上架？")->field("status")->isRequire(1);

        $formData = $form->create($this->generateUrl("admin_api_cms_tutorial_edit", ['id' => $id]));
        return $this->content()->renderEdit($formData);
    }


    public function editDoAction($id, Request $request, TutorialService $tutorialService)
    {
        $name = $request->get("name");
        $bigImg = $request->get("bigImg");
        $descr = $request->get("descr");
        $categoryId = (int) $request->get("categoryId");
        $type = (int) $request->get("type");
        $status = $request->get("status");
        $sort = (int) $request->get("sort");
        $status = $status == "on" ? 1 : 0;

        if (!$name) return $this->responseError("教程名称不能为空!");
        if (mb_strlen($name, 'utf-8') > 50) return $this->responseError("教程名称不能大于50字!");
        if ($categoryId <= 0) return $this->responseError("请选择分类!");
        $tutorialService->edit($id, $name, $type, $bigImg, $descr, $categoryId, $status, $sort);

        return $this->responseMsgCloseTab("操作成功!");
    }


    public function deleteDoAction($id, TutorialService $tutorialService)
    {
        if ($tutorialService->hasChapter($id)) return $this->responseError("删除失败，请先删除子章节!");
        $tutorialService->del($id);
        return $this->responseMsgRedirect("删除成功!", $this->generateUrl("admin_cms_tutorial_index"));
    }


    public function bathDeleteDoAction(Request $request, TutorialService $tutorialService)
    {
        $ids = $request->get("ids");
        if($ids){
            foreach ($ids as $id){
                if ($tutorialService->hasChapter($id)) return $this->responseError("删除失败，请先删除子章节!");
                $tutorialService->del($id);
            }
        }

        return $this->responseMsgRedirect("删除成功!", $this->generateUrl("admin_cms_tutorial_index"));
    }


    public function switchStatusAction($id, TutorialService $tutorialService, Request $request)
    {
        $state = $request->get("state");
        $tutorialService->switchStatus($id, $state);
        return $this->responseMsgRedirect("操作成功!");
    }
}
